package com.hula.onion.book.server.spider.platforms.liyedai;

import com.hula.onion.book.server.common.LoginForm;
import com.hula.onion.book.server.config.JedisUtils;
import com.hula.onion.book.server.config.SysConstants;
import com.hula.onion.book.server.model.AccountInfo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Description:
 * Create Date:2018/1/30 19:49
 *
 * @author liangbing
 * @version 1.0
 */
@Component
public class LiYeDaiSpiderHelper {

    /**
     * 组装请求参数
     *
     * @param form
     * @return
     */
    public Map<String, Object> installRequestParams(LoginForm form) {

        Map<String, Object> map = new HashMap<>(4);

        map.put("name", form.getUserName());
        map.put("password", form.getPassword());
        map.put("code", form.getTicket());

        //从缓存中获取randomId值
        String key = SysConstants.REDIS_KEY_PRE + SysConstants.LYD_RANDOM_ID
                + form.getPlatformId() + ":" + form.getUserId();

        map.put("randomID", JedisUtils.getInstance().get(key));

        return map;
    }

    /**
     * 解析账户余额
     *
     * @param html
     * @return
     */
    public AccountInfo parseAccountBalance(String html) throws Exception{

        AccountInfo accountInfo = new AccountInfo();

        if (!StringUtils.isEmpty(html)) {

            Document dc = Jsoup.parse(html);
            dc.selectFirst("p.asset-total").childNode(1);
            String amount = dc.selectFirst("p.asset-total").childNode(0).outerHtml().substring(1);

            accountInfo.setAmount(new BigDecimal(amount));

            String totalIntrest = dc.selectFirst("p.asset-history").childNode(0).outerHtml().substring(1);
            accountInfo.setTotalIntrest(new BigDecimal(totalIntrest));

        }else {
            throw new Exception();
        }

        return accountInfo;
    }


}
